package com.tarena.lbs.user.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.dao.mapper.UserTagsMapper;
import com.tarena.lbs.user.pojo.param.UserTagsParam;
import com.tarena.lbs.user.pojo.po.UserTagsPO;
import com.tarena.lbs.user.service.UserTagsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户标签服务实现
 */
@Service
@Slf4j
public class UserTagsServiceImpl implements UserTagsService {

    @Autowired
    private UserTagsMapper userTagsMapper;

    @Override
    public void bindUserTags(UserTagsParam param) throws BusinessException {
        // 1. 获取用户ID（优先从参数取，无则从登录信息取）
        Integer userId = param.getUserId();
        if (userId == null) {
            UserPrinciple principle = AuthenticationContextUtils.get();
            Asserts.isTrue(principle == null, new BusinessException("-2", "用户未登录"));
            userId = principle.getId();
        }
        // 关键：声明为 final，让 Lambda 能正确引用
        final Integer finalUserId = userId;

        // 2. 校验标签ID
        Asserts.isTrue(StringUtils.isBlank(param.getTagIds()), new BusinessException("-2", "标签ID不能为空"));
        List<String> tagIdList = Arrays.asList(param.getTagIds().split(","));
        Asserts.isTrue(CollectionUtils.isEmpty(tagIdList), new BusinessException("-2", "标签ID格式错误"));

        // 3. 绑定标签（实际业务中需先删除旧关联）
        List<UserTagsPO> tagsPOList = tagIdList.stream()
                .map(tagId -> {
                    UserTagsPO tagsPO = new UserTagsPO();
                    // 这里用 finalUserId，而不是原来的 userId
                    tagsPO.setUserId(finalUserId);
                    tagsPO.setTagId(Integer.parseInt(tagId));
                    return tagsPO;
                })
                .collect(Collectors.toList());

        // 4. 批量保存
        tagsPOList.forEach(tagsPO -> userTagsMapper.insert(tagsPO));
    }
}
